import { TokenMgr } from './TokenMgr';
import { ISocket } from './ISocket';
import * as io from 'socket.io';
import { LCrypto } from '../utils/lcrypto';
export class SocketService {
    config:any;
    mgr:any;
    sio: SocketIO.Server;
    constructor(config:any,mgr:any) {
        this.config=config;
        this.mgr=mgr;
        this.sio = io.listen(3913);
        this.sio.sockets.on("connection", (socket: ISocket) => this.connectionHandler(socket));
    }

    private connectionHandler(socket: ISocket): void {
        socket.on('login', (data) => this.loginHandler(data, socket))
    }
    private loginHandler(data: any, socket: ISocket): void {
        data = JSON.parse(data);
        if (!!!socket.userId) {
            //已经登陆过的就忽略
        }
        var token = data.token;
        var roomId = data.roomid;
        var time = data.time;
        var sign = data.sign;

        console.log(roomId);
        console.log(token);
        console.log(time);
        console.log(sign);
        //检查参数合法性
        if (token == null || roomId == null || sign == null || time == null) {
            console.log(1);
            socket.emit('login_result', { errcode: 1, errmsg: "invalid parameters" });
            return;
        }

        //检查参数合法性
        var md5=LCrypto.md5(roomId + token + time + this.config.ROOM_PRI_KEY);
        if(md5!=sign)
        {
            console.log(2);
            socket.emit('login_result',{errcode:2,errmsg:"login failed. invalid sign!"});
            return;
        }

        //检查token是否有效
			if(TokenMgr.isTokenValid(token)==false){
				console.log(3);
				socket.emit('login_result',{errcode:3,errmsg:"token out of time."});
				return;
			}
    }
}